import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
from sklearn.neural_network import MLPClassifier
import matplotlib.pyplot as plt

# 读取数据
data = pd.read_csv('cleaned_Spambase.csv')

# 划分特征和标签
X = data.iloc[:, :-1]  # 获取除最后一列之外的所有列作为特征X
y = data.iloc[:, -1]   # 获取最后一列作为标签y

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 数据标准化
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# 设置超参数
hidden_layer_sizes = (10,)    # 隐藏层大小
max_iter = 1000               # 最大迭代次数
solver = 'sgd'                # 优化器
learning_rate_init = 0.1      # 初始学习率
random_state = 42             # 随机种子

# 构建BP神经网络模型
bpnn_model = MLPClassifier(hidden_layer_sizes=hidden_layer_sizes, max_iter=max_iter, solver=solver,
                           learning_rate_init=learning_rate_init, random_state=random_state)

# 训练BP神经网络模型
bpnn_model.fit(X_train, y_train)

# 使用BP神经网络模型进行分类
y_pred_bpnn = bpnn_model.predict(X_test)

# 计算准确率
accuracy_bpnn = accuracy_score(y_test, y_pred_bpnn)
print("Accuracy (BP Neural Network): ", accuracy_bpnn)


# 设置模型名称和准确率
models = ['BP Neural Network']
accuracies = [accuracy_bpnn]

# 创建图表
plt.figure(figsize=(6, 4))
plt.bar(models, accuracies)
plt.ylim(0, 1)  # 设置 y 轴范围为 0 到 1
plt.xlabel('Model')
plt.ylabel('Accuracy')
plt.title('Accuracy Comparison')
plt.show()
